package com.example.deepai.controller;

import com.example.deepai.model.TestCase;
import com.example.deepai.repository.TestCaseRepository;
import com.example.deepai.service.ScreenCaptureService;
import com.example.deepai.service.UIRecognitionService;
import com.example.deepai.service.TestCaseGenerationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/testcase")
@RequiredArgsConstructor
public class TestCaseController {

    private final TestCaseRepository testCaseRepository;
    private final ScreenCaptureService screenCaptureService;
    private final UIRecognitionService uiRecognitionService;
    private final TestCaseGenerationService testCaseGenerationService;

    @PostMapping("/capture")
    public ResponseEntity<?> captureScreen() {
        try {
            // 修改为新的方法名，支持 Android 和鸿蒙设备
            String screenshotPath = screenCaptureService.captureScreen();
            return ResponseEntity.ok(Map.of("screenshotPath", screenshotPath));
        } catch (Exception e) {
            log.error("截图失败", e);
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }

    @PostMapping
    public ResponseEntity<TestCase> createTestCase(@RequestBody TestCase testCase) {
        TestCase savedTestCase = testCaseRepository.save(testCase);
        return ResponseEntity.ok(savedTestCase);
    }

    @GetMapping
    public ResponseEntity<List<TestCase>> getAllTestCases() {
        return ResponseEntity.ok(testCaseRepository.findAll());
    }

    @GetMapping("/{id}")
    public ResponseEntity<TestCase> getTestCase(@PathVariable Long id) {
        return testCaseRepository.findById(id)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }

    @PostMapping("/recognize")
    public ResponseEntity<?> recognizeUI(@RequestBody Map<String, String> request) {
        try {
            String screenshotPath = request.get("screenshotPath");
            log.info("开始UI识别，截图路径: {}", screenshotPath);
            
            Map<String, Object> uiStructure = uiRecognitionService.recognizeUI(screenshotPath);
            
            // 修改返回格式，添加rawResponse字段以匹配前端期望
            return ResponseEntity.ok(Map.of(
                "success", true,
                "rawResponse", new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(uiStructure),
                "timestamp", System.currentTimeMillis()
            ));
        } catch (Exception e) {
            log.error("UI识别失败", e);
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }

    @PostMapping("/generate")
    public ResponseEntity<?> generateTestCase(@RequestBody Map<String, Object> request) {
        try {
            com.fasterxml.jackson.databind.ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
            String uiStructureJson = mapper.writeValueAsString(request.get("uiStructure"));
            
            TestCase testCase = testCaseGenerationService.generateTestCase(
                uiStructureJson,
                (String) request.get("name"),
                (String) request.get("description")
            );
            
            return ResponseEntity.ok(testCase);
        } catch (Exception e) {
            log.error("生成测试用例失败", e);
            return ResponseEntity.internalServerError().body(Map.of("error", e.getMessage()));
        }
    }
    
    // 删除 generateTestCaseStream 方法
}